<?php

/**
 # com_jvframwork - JV Framework
 # @version		1.5.x
 # ------------------------------------------------------------------------
 # author    Open Source Code Solutions Co
 # copyright Copyright (C) 2011 joomlavi.com. All Rights Reserved.
 # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL or later.
 # Websites: http://www.joomlavi.com
 # Technical Support:  http://www.joomlavi.com/my-tickets.html
-------------------------------------------------------------------------*/
// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
jimport('joomla.application.component.helper');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.archive');
jimport('joomla.filesystem.path');


/**
 * Default Model
 *
 * @package   Joomla
 * @subpackage  Updater
 * @since   1.5
 */
class JVframeworkModelDefault extends JVModel {

    public $_filter_order = 'filter_order';
    public $_filter_order_Dir = 'filter_order_Dir';
    public $_key = 'id';
    public $_themelist = null;
    protected $themefile;


    /**
     * Construct method
     * 
     * @return void
     */
    function __construct() {
        parent::__construct();
    }
    
    function _buildQuery() {
        $query = "
				SELECT *					
				FROM #__jv_themes
				";
        return $query;
    }
    
    function duplicate(){
        $row = &$this->getTable();      
        $row->load($this->_id[0]);
        
        $data['id']     = 0; 
        $data['home']   = 0; 
        $data['params'] = $row->params; 
        $data['theme']  = current(explode('|', $row->theme)).'|'.current(explode('|', $row->theme)).' copy '.rand(1,99);
                
        if(!$row->save($data)){
            $this->setError($this->_db->getErrorMsg());
            return false;
        }  
        return true;
    }
    
    function writeFontLists(){    
        $content  = $this->getContent("http://www.google.com/webfonts")."\n"; // From URL to get webpage contents.
        $content .= $this->getContent("http://www.google.com/webfonts?subset=khmer")."\n"; // From URL to get webpage contents.
        $content .= $this->getContent("http://www.google.com/webfonts?subset=greek")."\n"; // From URL to get webpage contents.
        $content .= $this->getContent("http://www.google.com/webfonts?subset=cyrillic"); // From URL to get webpage contents.
          
        if(!JFile::write(JPATH_COMPONENT_ADMINISTRATOR.DS.'libraries/addons/gfont/font.ini', $content)) return;
        
        return true;
    }
    
    function getContent($url){        
        $ch = curl_init(); // Initialize a CURL session.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return Page contents.
        curl_setopt($ch, CURLOPT_URL, $url); // Pass URL as parameter.
        $content = curl_exec($ch); // grab URL and pass it to the variable.
        curl_close($ch); // close curl resource, and free up system resources.
        
        $regex ='/<\s*ul[^>]*id="fontlist"[^>]*>(.*?)<\s*\/\s*ul>/i';
        $content = str_replace(array("\t", "\r\n", "\n"), '', $content);
        preg_match_all($regex, $content, $match);
        $regex ='/<\s*span>(.*?)<\s*\/\s*span>/i';
        preg_match_all($regex, $match[1][0], $match); 
        
        $fontlist = array();
        
        if(count($match[1])){
            foreach($match[1] as $ma){
                if(preg_match('/[a-zA-Z]/', $ma)){
                    $fontlist[] = preg_replace('/\(.*\)/', '', $ma);
                }
            }
            
        }
        
        if(!count($fontlist)) return;
        
        $content = implode("\n",$fontlist);
        
        return $content;
    }
    
    /**
     * Get theme list
     *
     * @access	public
     * @return	array $themeList
     */
    function getThemeList() {
        $datas =& $this->getData(); 
                
        if($this->_themelist == null){            
            $this->_themelist = array();
            $themelist = array();
            
            if(!$themelist = JFolder::folders(JVPATH_THEME)){
                JError::raiseWarning(21, 'Template not found, please install JV-Framework template !!!');
                return false;
            }
            
            if(count($themelist)){
                foreach($themelist as $key => $theme){
                    if(JFile::exists(JVPATH_THEME.$theme.DS.'themeInfo.xml')){
                        $this->_themelist[$theme] = $this->getInfo($theme);
                        $this->_themelist[$theme]['theme'] = $theme;
                    }
                }
            }
            
            if(count($datas) && count($themelist)){
                foreach($datas as $data){
                    if(stripos($data->theme, '|')){
                        $themename                = explode('|', $data->theme);
                        $data->theme              = $themename[0].'-'.$data->id;
                        
                        if(isset($this->_themelist[$themename[0]])){
                            $this->_themelist[$data->theme] = $this->_themelist[$themename[0]];
                            $this->_themelist[$data->theme]['name'] = $themename[1].'<br />&nbsp;&nbsp;|__&nbsp;( theme: '.$this->_themelist[$data->theme]['theme'].' )';    
                        }
                    }
                    
                    $this->_themelist[$data->theme]['id']         = $data->id;
                    $this->_themelist[$data->theme]['home']       = $data->home;
                    $this->_themelist[$data->theme]['params']     = $data->params;
                    $this->_themelist[$data->theme]['published']  = $data->published;
                    
                }
            }
        }       
        
        return $this->_themelist;
    }
    
    
    /**
     * Get theme info
     *
     * @access	public
     * @param   string $theme theme name
     * @return	array $info
     */
    function getInfo($theme){           
        $info =& JApplicationHelper::parseXMLInstallFile(JVPATH_THEME.$theme.DS.'themeInfo.xml'); 
        return $info;
    }
    
    /**
     * Make default theme
     *
     * @access	public
     */
    function makeDefault(){        
        $this->removeOldAssign($this->_id[0]);
        $this->_db->setQuery("
            UPDATE #__jv_themes SET home=0 WHERE home=1
        ");
        $this->_db->query();
        
        $row = &$this->getTable();      
        $row->load($this->_id[0]);
        $row->home = 1;
        $params =@ json_decode($row->params) ; unset($params->menuassign);
        $row->params = json_encode($params);       
        
        if(!$row->store()){
            $this->setError($this->_db->getErrorMsg());
            return false;
        }  
        return true;
    }
    
    function getDefaultTheme(){
         $this->_db->setQuery("SELECT * FROM #__jv_themes WHERE home=1");
         return $this->_db->loadRow();
    }    
    
    /**
     * Method to store a record
     *
     * @access	public
     * @param   array $data
     * @return	boolean	True on success
     */
    function store($data) {
        if(preg_match('/[a-zA-Z]/',$data['id'])){
            $data['theme'] = $data['id'];
            unset($data['id']);
        }
        
        if(isset($data['themename']) && $data['theme']){
            $data['theme'] = $data['theme'].'|'.$data['themename'];
        }
        
        $row = &$this->getTable();   
        $menuAssign = array();
        
        if(!isset($data['params']['menuassign'])){
            $this->removeOldAssign($data['id']);
        } else {
            $menuAssign = $data['params']['menuassign'];
        }
           
        $data['params'] = json_encode($data['params']);        
        if(!$row->save($data)){
            $this->setError($this->_db->getErrorMsg());
            return false;
        }
        
        $this->_db->setQuery('SELECT id FROM #__jv_themes  WHERE theme=\''.$data['theme'].'\'');
        $data['id'] = $this->_db->loadResult();
        
        if($this->removeOldAssign($data['id'],$menuAssign) && count($menuAssign)){
            foreach($menuAssign as $menuid){
                $assign =& $this->getTable('assign');            
                $assignData = array('menuid'=>$menuid,'themeid'=>$data['id']);
                
                if(!$assign->save($assignData)){
                    $this->setError($this->_db->getErrorMsg());
                    return false;
                }                
            }
        }  
        
        $key = $this->_key;
        $this->id = $row->$key;
                
        return true;
    }
    
    /**
     * Remove Old Assign
     *
     * @access	public
     * @param   string $theme theme name
     * @param   array  $menuAssign 
     * 
     * @return	array  $info
     */
    function removeOldAssign($themeid, $menuAssign = array()){
        
        //Remove all assigned items for this theme.
        $this->_db->setQuery("
            DELETE FROM #__jv_theme_assign WHERE themeid='".$themeid."';                       
        ");
        $this->_db->query();
        
        //Remove all assigned menu items to other theme. 
        if(count($menuAssign) && is_array($menuAssign)){
            foreach($menuAssign as $menuid){
                $this->_db->setQuery("SELECT id FROM #__jv_theme_assign WHERE menuid='".$menuid."'");
                $resufts = $this->_db->loadObject();
                
                if($resufts){
                    $assign =& $this->getTable('assign');        
                    if(!$assign->delete($resufts->id)){
                        $this->setError($this->_db->getErrorMsg());
                        return false;
                    }
                }
            }
        }
               
        return true;
    }
    
   function getThemeAssignList($themeid){ 
         $this->_db->setQuery("SELECT menuid FROM #__jv_theme_assign WHERE themeid='".$themeid."'");
         return $this->_db->loadResultArray(0); 
    }
    
    /**
	 * Method to get default template name.
	 *
	 * @return	template
	 */
    public function getDefaultTemplate(){
        $db    = $this->getDbo();
        $query = $db->getQuery(true);        
        $query->select('template');
        $query->from('#__template_styles');
        $query->where('client_id = 0');
        $query->where('home = 1');
        
        $db->setQuery((string) $query);        
        return $db->loadResult();
        
    }
    
    /**
	 * Method to set template to default.
	 *
	 * @return	bool.
	 * @since	1.6
	 */
    public function setDefault(){
        $this->unsetDefaultTemplate();                
        $db = $this->getDbo();
        $query = $db->getQuery(true);        
        $query->update('#__template_styles');
        $query->set('`home` = 1');
        $query->where('client_id = 0');
        $query->where('template = '.$db->quote('jv-framework'));
        $db->setQuery((string) $query ." LIMIT 1");
        $db->query();
        
        return true;
    }
    
    /**
	 * Method to unset default template.
	 *
	 * @return	bool.
	 * @since	1.6
	 */
    public function unsetDefaultTemplate(){
        $db    = $this->getDbo();
        $query = $db->getQuery(true);        
        $query->update('#__template_styles');
        $query->set('`home` = 0');
        $query->where('client_id = 0');
        $query->where('`home` = 1');        
        $db->setQuery((string) $query);
        $db->query();
        
        return true;
    }
    
    function reset(){
        $theme = JRequest::getVar('id');
        
        if($theme == '') return;
        
        $this->_db->setQuery("
            UPDATE #__jv_themes 
            SET `params` = '' 
            WHERE `id` = '$theme'
        ");
        $this->_db->query();
        
        return true;
    }
    
    function &getParamList(){ 
        $data = $this->getTable();
        $data->load($this->_id[0]);         
        $theme = current(explode('|', $data->theme));
        
        if($data->params == 'null' || $data->params == ''){
            $params = $this->getDefaultThemeParams($theme);
        }else{
            $params =@ json_decode($data->params) ;
            $params->menuassign = $this->getThemeAssignList($this->_id[0]);
            $params = json_encode($params);
        }
        
        $parameter['mobile']        = new JVParameter($params,JPATH_COMPONENT.DS.'models'.DS.'forms'.DS.'mobile.xml');
        $parameter['gfont']         = new JVParameter($params,JPATH_COMPONENT.DS.'models'.DS.'forms'.DS.'gfont.xml');
        $parameter['global']        = new JVParameter($params,JPATH_COMPONENT.DS.'models'.DS.'forms'.DS.'global.xml');
        $parameter['layoutsetting'] = new JVParameter($params,JPATH_COMPONENT.DS.'models'.DS.'forms'.DS.'layoutsetting.xml');
        $parameter['menusystem']    = new JVParameter($params,JPATH_COMPONENT.DS.'models'.DS.'forms'.DS.'menusystem.xml');
              
        return $parameter;
    }
    
    function getDefaultThemeParams($theme){
        $path = JVPATH_THEME.$theme.DS.'params.json';
        $param= '';
        if(JFile::exists($path)){
            $param = JFile::read($path);
        }
        if($param == '') return;
        return $param;
    }
   
    function &getMenu(){
    	// build the html select list
    	$options = JHTML::_('menu.linkoptions');        
        return $options;
    }
    
    function clearCache(){
        $cachetype  = JRequest::getVar('cachetype');
        $theme = JRequest::getVar('theme');        
        $cache_path = JVPATH_THEME . $theme . DS . 'cache' .DS;
        $files = JFolder::files($cache_path, '.', 0, true);
        
        if($cachetype == 'css'){
            if(is_array($files)){
                foreach($files as $file){
                    if(preg_match('/css/', $file)){
                        if(!JFile::delete($file)){
                            JError::raiseWarning('Cannot delete cache file, please check file permission!');
                        }
                    }
                }
            }
        }else {
            if(is_array($files)){
                foreach($files as $file){
                    if(preg_match('/js/', $file)){
                        if(!JFile::delete($file)){
                            JError::raiseWarning('Cannot delete cache file, please check file permission!');
                        }
                    }
                }
            }
        }                            
        return true;                    
            
    }  
    
    function loadLayout(){
        $id         = JRequest::getVar('id');
        $theme      = JRequest::getVar('theme');
        $layoutname = JRequest::getVar('layoutname');       
        $customlayoutpath = JVPATH_THEME . $theme . DS . 'customlayouts' .DS;        
        $content =@ JFile::read($customlayoutpath.$layoutname);
        
        $row = &$this->getTable();      
        $row->load($id);        
        $params =@ json_decode($row->params) ;
        
        $params->layoutsetting = $content;
        $row->params = json_encode($params);       
        
        if(!$row->store()){
            $this->setError($this->_db->getErrorMsg());
            return false;
        }  
        return true;       
    }      
    
    function saveLayout(){
        $theme      = JRequest::getVar('theme');
        $layoutname = JRequest::getVar('layoutname'); 
        $data       = JRequest::get('post');    
        $layoutsetting    = $data['params']['layoutsetting'];      
        $customlayoutpath = JVPATH_THEME . $theme . DS . 'customlayouts' .DS;   
        
        if(!JFolder::exists($customlayoutpath)){
            if(!JFolder::create($customlayoutpath)) return false;
        }
        
        if(!JFile::write($customlayoutpath.$layoutname.'.xml',$layoutsetting)) return false;
            
        return true;        
    }
          
    function deleteLayout(){
        $theme      = JRequest::getVar('theme');
        $layoutname = JRequest::getVar('layoutname');       
        $customlayoutpath = JVPATH_THEME . $theme . DS . 'customlayouts' .DS; 
        
        if(!JFile::delete($customlayoutpath.$layoutname)) return false;
        
        return true;        
    }  
    
    function doActive(){
        $data = array();
        $row =& $this->getTable();
        
        if(preg_match('/[a-zA-Z]/',$this->_id[0])){
            $data['theme'] = $this->_id[0];
            if(!$row->save($data)){
                $this->setError($this->_db->getErrorMsg());
                return false;
            }
            
        } else {
            $row->load($this->_id[0]);
            $row->home = 0;
            
            if(!$row->store()){
                $this->setError($this->_db->getErrorMsg());
                return false;
            }
        }
      
        return true;
    }   
    
    function doDeactive(){
        $row =& $this->getTable();
        $this->removeOldAssign((int)$this->_id[0]);
        if(!$row->delete((int)$this->_id[0])){
            $this->setError($this->_db->getErrorMsg());
            return false;
        }
        
        return true;
    }  
    
    function getThemeFile(){
        $themefile = array();
        
        if($this->themefile == array()){
            $data =& $this->getTable();
            $data->load((string)$this->_id[0]);
            $theme = current(explode('|', $data->theme));
            
            if(!is_writable(JVPATH_THEME.$theme.DS.'cache')){
                JError::raiseWarning(21,'Directory themes'.DS.$theme.DS.'cache is not writable, please make it writable!!');
                return;
            }
            $filter = 'xml|css|js|ini';
            
            $themefile['css']     = JFolder::exists(JVPATH_THEME.$theme.DS.'css') ? JFolder::files(JVPATH_THEME.$theme.DS.'css',$filter) : array();
            $themefile['js']      = JFolder::exists(JVPATH_THEME.$theme.DS.'js') ? JFolder::files(JVPATH_THEME.$theme.DS.'js',$filter) : array();
            $themefile['layouts'] = JFolder::exists(JVPATH_THEME.$theme.DS.'layouts') ? JFolder::files(JVPATH_THEME.$theme.DS.'layouts',$filter) : array();
            $themefile['mobiles']['android'] = JFolder::exists(JVPATH_THEME.$theme.DS.'mobiles'.DS.'android') ? JFolder::files(JVPATH_THEME.$theme.DS.'mobiles'.DS.'android',$filter) : array();
            $themefile['mobiles']['iphone'] = JFolder::exists(JVPATH_THEME.$theme.DS.'mobiles'.DS.'iphone') ? JFolder::files(JVPATH_THEME.$theme.DS.'mobiles'.DS.'iphone',$filter) : array();
            $themefile['mobiles']['handheld'] = JFolder::exists(JVPATH_THEME.$theme.DS.'mobiles'.DS.'handheld') ? JFolder::files(JVPATH_THEME.$theme.DS.'mobiles'.DS.'handheld',$filter) : array();
            $themefile['googlefont']    = JFolder::exists(JVPATH_THEME.$theme.DS.'googlefont') ? JFolder::files(JVPATH_THEME.$theme.DS.'googlefont',$filter) : array();
            $themefile['customlayouts'] = JFolder::exists(JVPATH_THEME.$theme.DS.'customlayouts') ? JFolder::files(JVPATH_THEME.$theme.DS.'customlayouts',$filter) : array();
            $themefile['special_css']   = JFolder::exists(JVPATH_THEME.$theme.DS.'special_css') ? JFolder::files(JVPATH_THEME.$theme.DS.'special_css',$filter) : array();
            $themefile['root']          = JFolder::exists(JVPATH_THEME.$theme) ? JFolder::files(JVPATH_THEME.$theme,$filter) : array();
            $this->themefile = $themefile;
        }
        return $this->themefile;
    } 
    
    function readThemeFile(){
        $data = JRequest::get('post');
        $file = explode('|',$data['file']);    
        $folder= $file[1] == 'root' ? '': $file[1].DS;   
        $data['theme'] = current(explode('|', $data['theme']));
        if(!is_readable(JVPATH_THEME.$data['theme'].DS.$folder.$file[0])) return false;
        echo JFile::read(JVPATH_THEME.$data['theme'].DS.$folder.$file[0]);
        return true;
    }
    
    function saveThemeFile(){
        $code = JRequest::getVar('code','','post','STRING',JREQUEST_ALLOWRAW);
        $data = JRequest::get('post'); 
        $file = explode('|',$data['file']);   
        $folder= $file[1] == 'root' ? '': $file[1].DS;   
        $data['theme'] = current(explode('|', $data['theme']));
        if(!is_writeable(JVPATH_THEME.$data['theme'].DS.$folder.$file[0])) return false;
        if(!JFile::write(JVPATH_THEME.$data['theme'].DS.$folder.$file[0],$code)) return false;
        
        return true;
    }
    
    function upload(){
        $uploadPath = JPATH_ROOT.DS.'tmp';
        $files      = $_FILES['file_upload'];
        $fileType   = $files['type'];
        $filename   = $files['name'];
        $fileTemp   = $files['tmp_name'];
        $update     =& JModel::getInstance('update','JVframeworkModel');  
        $name       = explode('.',$filename); 
             
        if($files['error']) return;
        if(!JFile::upload($fileTemp, $uploadPath.DS.$filename)) return;
        if(!$update->unpack($uploadPath.DS.$filename, $uploadPath)) return;
        if(!JFile::delete($uploadPath.DS.$filename)) return;
        if(JFile::exists($uploadPath.DS.$name[0].DS.'themeInfo.xml') && JFile::exists($uploadPath.DS.$name[0].DS.'thumbnail.jpg'))
        if(!JFolder::copy($uploadPath.DS.$name[0].DS,JVPATH_THEME .DS.$name[0].DS,'',true)) return;
        if(!JFolder::delete($uploadPath.DS.$name[0].DS)) return;
       
        return true;
    }
    
    function transferfile(){
        $uploadPath = JPATH_ROOT.DS.'tmp';
        $fileUrl    = JRequest::getVar('file_tran');
        $fileExt    = explode('.',$fileUrl);
        $update     =&JModel::getInstance('update','JVframeworkModel');
        
        $filename = $update->downloadPackage($fileUrl);
        $name       = explode('.',$filename); 
        if(!$update->unpack($uploadPath.DS.$filename, $uploadPath.DS)) return;
        if(!JFile::delete($uploadPath.DS.$filename)) return;
        if(JFile::exists($uploadPath.DS.$name[0].DS.'themeInfo.xml') && JFile::exists($uploadPath.DS.$name[0].DS.'thumbnail.jpg'))
        if(!JFolder::copy($uploadPath.DS.$name[0].DS,JVPATH_THEME .DS.$name[0].DS,'',true)) return;
        if(!JFolder::delete($uploadPath.DS.$name[0].DS)) return;        
        return true;
    }
}
